<?php namespace Admin\Model;

use Hdphp\Model\Model;

class Goods extends Model{

	//数据表
	protected $table = "shop_goods";

	//完整表名
	protected $full = false;

	//自动验证
	protected $validate=array(
		//字段名: 表单字段名
		//验证方法: 函数或模型方法
		//验证条件: 1有字段时验证(默认)	2值不为空时验证  	3必须验证 
		//验证时间: 1 插入时验证		2更新时空时验证 	3全部情况验证 (默认)
		//array('字段名','验证方法','提示信息',验证条件,验证时间),
		array('goods_name','required','商品名称不能为空',3,3),
		array('goods_sn','required','商品货号不能为空',3,3),
		array('keyword','required','商品关键字不能为空',3,3),
		array('description','required','商品描述不能为空',3,3),
	);

	//自动完成
	protected $auto=array(
		array('create_at','time','function',3,1),
		array('admin_id','getAdminId','method',3,1),
		array('list_pic','getListPic','method',3,1),
		array('thumb_pic','getThumbPic','method',3,1),
	);

	//自建方法，获取管理员id
	public function getAdminId(){
		return $_SESSION['admin_id'];
	}

	//获取上传的列表图片路径
	public function getListPic()
	{
		$file = Upload::path('Upload/Goods')->make('list_pic');
		if($file){
			return $file[0]['path'];
		}
		return Q('post.list_pic','');
	}

	//获取缩略图的路径
	public function getThumbPic()
	{
		$file = Upload::path('Upload/Goods')->make('thumb_pic');
		if($file){
			return $file[0]['path'];
		}
		return Q('post.thumb_pic','');
	}

	//调数据 形参设置默认值
	public function  getAll($cat_id='')
	{
		if ($cat_id) 
		{
			//读取指定栏目商品
			// 获取数据，分页总数
			$page = Page::make($this->where('cat_id',$cat_id)->count());
			//合并表，获取数据
			$data = Db::table('shop_goods g')->where('c cat_id',$cat_id)->limit(Page::limit())->join('shop_cat c','g.cat_id','=','c.cat_id')->where('is_delete',0)->get();
		}
		else{
			//读取所有商品
			$page = Page::make($this->count());
			$data = Db::table('shop_goods g')->limit(page::limit())->join('shop_cat c','g.cat_id','=','c.cat_id')->where('is_delete',0)->get();
		}
		return array('data'=>$data,'page'=>$page);
	}

	// 添加商品
	public function store()
	{
		
		if($this->create())
		{
			if($goods_id = $this->add())
			{
				//上面添加生成了新数据后 插入的ID给变量$goods_id
				//执行下面代码段。实例化模型，执行模型方法
				$pic = new \Admin\Model\Pics;
				$pic->store($goods_id);

				//执行下面代码段。实例化模型，执行模型方法
				$goodAttr = new \Admin\Model\GoodsAttr;
				$goodAttr->addGoodsAttr($goods_id);

			}
			return true;
		}		
	}

	//编辑商品
	public function edit()
	{

		if ($this->create()) 
		{
			
			if($this->save())
			{
				$pic = new \Admin\Model\Pics;
				$pic->store($_POST['goods_id']);
				
				$goodAttr = new \Admin\Model\GoodsAttr;				
				$goodAttr->editGoodsAttr($_POST['goods_id']);

 			}
			return true;
		}
	}
	//放进回收站方法
	public function del($id)
	{
		$goods_id = $id;
		$data = $this->find($goods_id);
		$data['is_delete'] = '1';
		return $this->save($data);
	}

	//根据传入的商品ID找到对应数据
	public function only($goods_id)
	{
		return $this->find($goods_id);
	}

}